package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.entities.CartInfo;
import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ClassName CartRestController
 * @Description TODO
 * @Author king
 * @Date 2022/11/18 16:37
 * @Version 1.0
 * http://api.gmall.com/api/cart/cartList
 */
@Slf4j
@RestController
@RequestMapping("/api/cart")
public class CartRestController {

    @Autowired
    CartService cartService;

    //http://api.gmall.com/api/cart/deleteCart/56
    @DeleteMapping("/deleteCart/{skuId}")
    public Result deleteCart(@PathVariable ("skuId") Long skuId){

        String cartKey = cartService.determinCartKey();
        cartService.deleteCartItem(cartKey, skuId);

        return Result.ok();

    }

    @PostMapping("addToCart/{skuId}/{num}")
    public Result addCartInfo(@PathVariable ("skuId") Long skuId, @PathVariable("num") Integer num){

        String cartKey = cartService.determinCartKey();
        try{
            cartService.updateCartItemCount(cartKey, skuId, num);
        }catch (GmallException e){
            Result<Object> fail = Result.fail();

            fail.setCode(e.getCode());
            log.error("错误: {}", e);
            fail.setMessage(e.getMessage());
            return fail;
        }

        return Result.ok();
    }

    //修改状态
    @GetMapping("/checkCart/{skuId}/{status}")
    public Result checkCart(@PathVariable("skuId") Long skuId, @PathVariable("status") Integer status){

        String cartKey = cartService.determinCartKey();
        cartService.updateCartStatus(cartKey, skuId, status);

        return Result.ok();
    }

    @GetMapping("/cartList")
    public Result cartList(){

        String cartKey = cartService.determinCartKey();
        List<CartInfo> cartInfo = cartService.getCartList(cartKey);

        return Result.ok(cartInfo);
    }

}
